package com.net
{
	//https://apifox.com/apidoc/shared-e5a9a48b-3296-4470-a58c-bb28c51920cc/api-98639566
	import com.worlize.websocket.WebSocket;
	import com.worlize.websocket.WebSocketErrorEvent;
	import com.worlize.websocket.WebSocketEvent;
	import com.worlize.websocket.WebSocketMessage;
	
	import flash.events.*;
	import flash.external.ExternalInterface;
	import flash.utils.ByteArray;
	
	import game.GlobalConfig;
	import game.model.GameData;
	import game.model.type.NoticeCMD;
	import game.util.CarJsCall;
	import game.view.panel.other.LabelNoticeView;
	import game.view.component.SystemNotice;
	import morn.App;
	public class SocketManage
	{
		private static var s_instance:SocketManage;
		private static var isSing:Boolean=false;
		private var m_socket:WebSocket;
		public function SocketManage()
		{
			if(!isSing){
				throw new Error("SocketManage 只能实例一次");
			}
		}
		public static function get instance():SocketManage {
			if (s_instance == null){
				isSing=true;
				s_instance = new SocketManage();
				isSing=false;
			}
			return s_instance;
		}
		public function init(weburl:String):void{
			GC();
			this.m_socket=new WebSocket(weburl, "*");
			
			
			this.m_socket.debug = false;
			this.m_socket.s_securityPort=843;
			this.m_socket.addEventListener(WebSocketEvent.CLOSED, handleWebSocketClosed);
			this.m_socket.addEventListener(WebSocketEvent.OPEN, handleWebSocketOpen);
			this.m_socket.addEventListener(WebSocketEvent.MESSAGE, handleWebSocketMessage);
			this.m_socket.addEventListener(WebSocketEvent.PONG, handlePong);
			this.m_socket.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
			this.m_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityError);
			this.m_socket.addEventListener(WebSocketErrorEvent.CONNECTION_FAIL, handleConnectionFail);
			
			this.m_socket.connect();
		}
		
		private function handleIOError(event:IOErrorEvent):void {
			trace("SocketManage handleIOError");
		}
		
		private function handleSecurityError(event:SecurityErrorEvent):void {
			trace("SocketManage handleSecurityError");
			//ExternalInterface.call("SwfMessNotice",'handleSecurityError');
		}
		
		private function handleConnectionFail(event:WebSocketErrorEvent):void {
			trace("SocketManage handleConnectionFail");
			
		}
		
		private function handleWebSocketClosed(event:WebSocketEvent):void {
			trace("SocketManage handleWebSocketClosed");
			this.GC();
			CarJsCall.SwfMessNotice('handleWebSocketClosed');
			var ad:Object={mes:'链接已经断开，请重进...',closeBtn:false,'title':'链接错误'};
			ZooMain.controller.sendNotification(NoticeCMD.NOTICE_VIEW_ALERT,ad);	
			var labelV:LabelNoticeView=LabelNoticeView.instance;
			labelV.isToPiao=false;
			labelV.showNotice('链接已经断开，请重进...');
		}
		
		private function handleWebSocketOpen(event:WebSocketEvent):void {
			trace("SocketManage 开始登录.");
			//登录
			var params:Object={
				"userId": GlobalConfig.uid,
				"mcheck": GlobalConfig.userMeck	
			};
			var vo:Object={"cmd": "Login", "params": params};
			//console.log("NetWrok onOpen 开始登录",vo);
			
			this.sendUTF(JSON.stringify(vo));
		}
		
		public function sendUTF(str:String):void{
			if(this.m_socket!=null && this.m_socket.connected){
				trace('SocketManage sendUTF',str);
				CarJsCall.SwfMessNotice('sendUTF :'+str);
				this.m_socket.sendUTF(str);
			}
		}
		
		private function handleWebSocketMessage(event:WebSocketEvent):void {
			trace("SocketManage handleWebSocketMessage");
			if (event.message.type === WebSocketMessage.TYPE_UTF8) {
				if (this.m_socket.protocol === 'lws-mirror-protocol') {
					var commands:Array = event.message.utf8Data.split(';');
					for each (var command:String in commands) {
						if (command.length < 1) { continue; }
						var fields:Array = command.split(' ');
						var commandName:String = fields[0];
						if (commandName === 'c' || commandName === 'd') {
							var color:uint = parseInt(String(fields[1]).slice(1), 16);
							var startX:int = parseInt(fields[2], 10);
							var startY:int = parseInt(fields[3], 10);
							
							if (commandName === 'c') {
								// c #7A9237 487 181 14;
								var radius:int = parseInt(fields[4], 10);
								
							}
							else if (commandName === 'd') {
								var endX:int = parseInt(fields[4], 10);
								var endY:int = parseInt(fields[5], 10);
								
							}
							
						}
						else if (commandName === 'clear') {
							
						}
						else {
							WebSocket.logger("Unknown Command: '" + fields.join(' ') + "'");
						}
					}
				}
				else if (this.m_socket.protocol === 'dumb-increment-protocol') {
					
				}
				else {
					//WebSocket.logger("utf:"+event.message.utf8Data);
					this.messNotice(event.message.utf8Data);
				}
			}
			else if (event.message.type === WebSocketMessage.TYPE_BINARY) {
				WebSocket.logger("Binary message received.  Length: " + event.message.binaryData.length);
			}
		}
		private function handlePong(event:WebSocketEvent):void {
			trace("SocketManage handlePong");
		}
		/**服务器通知**/
		private function messNotice(mes:String):void{
			var respParams:Object=JSON.parse(mes);
			trace('SocketManage messNotice',mes);
			//trace('SocketManage messNotice',respParams.status,respParams.cmd);
			
			if(respParams.status===0){
				if(!GameData.instance.isLogin){
					App.timer.doLoop(55*1000,this.sendHear);
				}		
			}else{
				if(respParams.errorMsg!='')LabelNoticeView.instance.showNotice(respParams.errorMsg);
			}
			GameData.instance.CMD(respParams);
			ZooMain.controller.sendNotification(NoticeCMD.NOTICE+respParams.cmd,respParams);
			ZooMain.event.dispatchEvent(NoticeCMD.NOTICE+respParams.cmd,respParams);
			CarJsCall.SwfMessNotice(JSON.stringify(respParams));
		}
		private function sendHear():void{
			trace("SocketManage sendHear 心跳");
			var vo:Object={"cmd": "Heart", "params": {}};
			this.sendUTF(JSON.stringify(vo));
		}
		public function GC():void{
			if(this.m_socket!=null){
				this.m_socket.removeEventListener(WebSocketEvent.CLOSED, handleWebSocketClosed);
				this.m_socket.removeEventListener(WebSocketEvent.OPEN, handleWebSocketOpen);
				this.m_socket.removeEventListener(WebSocketEvent.MESSAGE, handleWebSocketMessage);
				this.m_socket.removeEventListener(WebSocketEvent.PONG, handlePong);
				this.m_socket.removeEventListener(IOErrorEvent.IO_ERROR, handleIOError);
				this.m_socket.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityError);
				this.m_socket.removeEventListener(WebSocketErrorEvent.CONNECTION_FAIL, handleConnectionFail);
				this.m_socket.close();
			}
			this.m_socket=null;
		}
	}
}